import subprocess
import sys


def get_file_name(path):
    index_l = path.rfind("/")
    index_r = path.rfind(".")
    return path[index_l + 1:index_r]


def get_test_data(file_io):
    block_data = b""
    line = file_io.readline().rstrip(b"\r")
    if line == b"":
        return None
    if line[0:2] == b"++":
        line = file_io.readline().rstrip(b"\r")
        while line[0:2] != b"--":
            block_data += line
            line = file_io.readline().rstrip(b"\r")
    return block_data


def format_data(data):
    return b'\t'+data.replace(b'\n', b'\n\t')


file_path = ""
file_src = ""
argv_len = len(sys.argv)
if argv_len >= 3:
    file_path = sys.argv[1]
    file_src = sys.argv[2]
elif argv_len:
    print("[ERROR] Need Args")
    sys.exit(1)
file_name = get_file_name(file_src)
in_file = "test/" + file_name + ".in"
out_file = "test/" + file_name + ".out"

print("===========Test Begin==========")
try:
    with open(in_file, "rb") as in_io:
        with open(out_file, "rb") as out_io:
            line = get_test_data(in_io)
            out_data = get_test_data(out_io).rstrip(b"\r\n")
            i = 1
            while line:
                with subprocess.Popen(file_path, stdin=subprocess.PIPE, stdout=subprocess.PIPE) as proc:
                    proc.stdin.write(line)
                    proc.stdin.flush()
                    proc_out = proc.stdout.read().rstrip(b" \r\n")
                    if proc_out != out_data:
                        print(f"{i}..............FAILED")
                        out_data = format_data(out_data)
                        proc_out = format_data(proc_out)
                        print("E:\n{}".format(out_data.decode('utf-8')))
                        print("G:\n{}".format(proc_out.decode('utf-8')))
                    else:
                        print(f"{i}..............PASSED")
                i += 1
                line = get_test_data(in_io)
                out_data = get_test_data(out_io)
                out_data = None if out_data is None else out_data.rstrip(b"\r\n")
except FileNotFoundError as e:
    print("File Not Found Skip Test")
print("===========Test End============")
